package com.wty.love.diary;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.wty.love.MainActivity;
import com.wty.love.R;
import com.wty.love.database.entity.Diary;

import java.text.SimpleDateFormat;
import java.util.Date;

public class LookDiaryActivity extends AppCompatActivity {
    public static String LOOKDIARY = "LOOKDIARY";
    public static String NOWPOSITION = "NOWPOSITION";
    private int position = 0;
    private Diary diary;
    private View back;
    private View save;
    private EditText title;
    private EditText weather;
    private EditText content;
    private EditText note;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_look_diary);
        initView();
        initData();
        initClicked();
    }
    private void initView(){
        back = findViewById(R.id.back);
        save = findViewById(R.id.save);
        title = findViewById(R.id.title);
        weather = findViewById(R.id.weather);
        content = findViewById(R.id.content);
        note = findViewById(R.id.note);
    }
    private void initData(){
        this.diary = (Diary) getIntent().getSerializableExtra(LOOKDIARY);
        position = getIntent().getIntExtra(NOWPOSITION,0);
        title.setText(diary.getTitle());
        weather.setText(diary.getWeather());
        content.setText(diary.getContent());
        note.setText(diary.getNote());
    }
    private void initClicked(){
        back.setOnClickListener(v->{onBackPressed();});
        save.setOnClickListener(v->{
            updateDiary();
        });
    }
    private void updateDiary(){
        String title = this.title.getText().toString();
        String weather = this.weather.getText().toString();
        String content = this.content.getText().toString();
        String note = this.note.getText().toString();
        String strDateFormat = "yyyy-MM-dd HH:mm:ss";
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat(strDateFormat);
        String createTime = sdf.format(new Date());

        diary.setTitle(title);
        diary.setWeather(weather);
        diary.setContent(content);
        diary.setNote(note);
        diary.setCreateTime(createTime);
        MainActivity.diaryDao.updateDiary(diary);
        Toast.makeText(this,"修改成功",Toast.LENGTH_SHORT).show();
        onBackPressed();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        LiveEventBus.get(MainActivity.SETDELETEPOSITION).post(position);
    }
}